package com.heima.wemedia.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.constants.message.NewsAutoScanConstants;
import com.heima.common.constants.message.NewsUpOrDownConstants;
import com.heima.common.constants.message.PublishArticleConstants;
import com.heima.common.constants.wemedia.WemediaConstants;
import com.heima.common.exception.CustException;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.threadlocal.WmThreadLocalUtils;
import com.heima.model.wemedia.dtos.NewsAuthDTO;
import com.heima.model.wemedia.dtos.WmNewsDTO;
import com.heima.model.wemedia.dtos.WmNewsPageReqDTO;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.model.wemedia.pojos.WmNewsMaterial;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.model.wemedia.vos.WmNewsVO;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.mapper.WmNewsMaterialMapper;
import com.heima.wemedia.mapper.WmUserMapper;
import com.heima.wemedia.service.WmNewsService;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Slf4j
public class WmNewsServiceImpl extends ServiceImpl<WmNewsMapper, WmNews>implements WmNewsService {
    //图片路径
    @Value("${file.oss.web-site}")
    private String webSite;

    @Autowired
    RabbitTemplate rabbitTemplate;

    /**自媒体文章查询实现
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult findList(WmNewsPageReqDTO dto) {
        //检查参数 分页 登录
        if (dto==null) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID,"请传入正确的参数");
        }
        //封装查询条件
        LambdaQueryWrapper<WmNews> wrapper = new LambdaQueryWrapper<>();
        //按照文章标题模糊查询
        if(StringUtils.isNotBlank(dto.getKeyword())){
            wrapper.like(WmNews::getTitle,dto.getKeyword());
        }
        //频道信息  按照频道id查询
        if(dto.getChannelId()!=null){
            wrapper.eq(WmNews::getChannelId,dto.getChannelId());
        }
        //如有状态 按照状态信息查询
        if(dto.getStatus()!=null){
            wrapper.eq(WmNews::getStatus,dto.getStatus());
        }
        //开始时间结束时间不为空
        if(dto.getBeginPubDate()!=null&&dto.getEndPubDate()!=null){
            wrapper.between(WmNews::getCreatedTime,dto.getBeginPubDate(),dto.getEndPubDate());
        }
        //按照登录用户id去查
        WmUser user = WmThreadLocalUtils.getUser();
        if(user==null){
            CustException.cust(AppHttpCodeEnum.NEED_LOGIN,"您还未登录");
        }
        wrapper.eq(WmNews::getUserId,user.getId());
        //按照创建时间降序
        wrapper.orderByDesc(WmNews::getCreatedTime);
        //执行分页查询
        Page<WmNews> page = new Page<>(dto.getPage(),dto.getSize());
        IPage<WmNews> pageResult = page(page, wrapper);
        //封装响应结果  host: 图片访问前缀
        PageResponseResult result = new PageResponseResult(dto.getPage(), dto.getSize(), pageResult.getTotal());
        result.setData(pageResult.getRecords());
        //图片响应前缀
        result.setHost(webSite);
        return result;
    }

    /** 文章发布功能实现
     *
     * @param dto
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public ResponseResult submitNews(WmNewsDTO dto) {
        //1.将dto转化为wmNews对象
        //1.1 校验参数(content 登录)
        if(StringUtils.isBlank(dto.getContent())){
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID,"请传入正确的参数");
        }
        //1.2 将dto的属性值拷贝到wmnews对象
        WmNews wmNews = new WmNews();
        BeanUtils.copyProperties(dto,wmNews);
        //1.3如果type等于-1 暂时设置type为null
        if(dto.getType().equals(WemediaConstants.WM_NEWS_TYPE_AUTO)){
         wmNews.setType(null);
        }
        //1.4 封面dto传入的是list<String> 图片集合  转化为字符串逗号拼接
        String imageStr = imageListToStr(dto.getImages(),webSite);
        wmNews.setImages(imageStr);
        //2.保存或修改文章 抽取方法saveOrUpdate
        saveOrUpdateWm(wmNews);
        //3.保存 文章内容 或封面 和 素材的关联关系
        //抽取文章内容中所有的素材url路径集合
        List<Map> contentMaps = JSON.parseArray(dto.getContent(), Map.class);
        System.out.println(contentMaps);
        //抽取方法返回图片路径集合
        List<String> contentUrls =   parseContentImages(contentMaps);
        System.out.println(contentUrls);
        //保存文章和素材的关联关系
        //判断文章是否引用图片素材
        if(CollectionUtils.isNotEmpty(contentUrls)){
            saveRelativiInfo(contentUrls,wmNews.getId(),WemediaConstants.WM_CONTENT_REFERENCE);
        }
        //
        if(dto.getStatus()==WmNews.Status.SUBMIT.getCode()){
            saveRelativeInfoForCover(dto,contentUrls,wmNews);
        }
        //发送自动审核消息到mq
        rabbitTemplate.convertAndSend(NewsAutoScanConstants.WM_NEWS_AUTO_SCAN_QUEUE,wmNews.getId());
        log.info("成功发送 待审核消息");

        return ResponseResult.okResult();
    }

    /**根据id查询文章
     * @param id
     * @return
     */
    @Override
    public ResponseResult findWmNewsById(Integer id) {
        //数据检查
        if(id==null){
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID,"请传入正确参数");
        }
        //执行查寻
        WmNews wmNews = getById(id);
        if(wmNews==null){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"您还未发布文章");
        }

        //结果封装
        ResponseResult result = ResponseResult.okResult(wmNews);
        result.setHost(webSite);
        return result;
    }

    /**根据文章id删除文章
     *
     * @param id
     * @return
     */
    @Override
    public ResponseResult delNews(Integer id) {
        //参数检查
        if(id==null){
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID,"文章id不存在");
        }
        //根据id先将文章查询出来
        WmNews wmNews = getById(id);
        if(wmNews==null){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"文章不存在");
        }
        //判断当前文章状态
        if(WemediaConstants.WM_NEWS_PUBLISH_STATUS.equals(wmNews.getStatus())&&WemediaConstants.WM_NEWS_UP.equals(wmNews.getEnable())){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW,"文章发布上架状态不可删除");
        }
        //删除素材与文章关系
        wmNewsMaterialMapper.delete(Wrappers.<WmNewsMaterial>lambdaQuery().eq(WmNewsMaterial::getMaterialId,id));
        //删除文章
        removeById(wmNews.getId());
        return ResponseResult.okResult();
    }


    /**文章上下架功能
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult downOrUp(WmNewsDTO dto) {
        //数据检查
        if (dto.getId()==null||dto==null) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID,"请传入正确的参数");
        }
        //根据id查询文章
        WmNews wmNews = getById(dto.getId());
        if(wmNews==null){
           CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"文章不存在");
        }
        //3.判断文章是否发布
        if(!WemediaConstants.WM_NEWS_PUBLISH_STATUS.equals(wmNews.getStatus())){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW,"当前文章非发布状态不能上下架");
        }
        //4.修改文章状态，
        update(Wrappers.<WmNews>lambdaUpdate().eq(WmNews::getId,dto.getId())
                .set(WmNews::getEnable,dto.getEnable()));

        //上下架发送消息通知
        //判断APP端文章Id是否存在
        if(wmNews.getArticleId()!=null){
            //判断是否为上架状态
            if(wmNews.getEnable().equals(WemediaConstants.WM_NEWS_UP)){
                //上架状态发送文章id
                rabbitTemplate.convertAndSend(NewsUpOrDownConstants.NEWS_UP_OR_DOWN_EXCHANGE,NewsUpOrDownConstants.NEWS_UP_ROUTE_KEY,wmNews.getArticleId());
            }else {
                rabbitTemplate.convertAndSend(NewsUpOrDownConstants.NEWS_UP_OR_DOWN_EXCHANGE,NewsUpOrDownConstants.NEWS_DOWN_ROUTE_KEY,wmNews.getArticleId());
            }

        }
        //TODO ES
        return ResponseResult.okResult();
    }

    @Autowired
    private WmNewsMapper wmNewsMapper;

    /**查询文章列表
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult findList(NewsAuthDTO dto) {
        //校验参数
        dto.checkParam();
        //分页设置  起始页
        Integer page = dto.getPage();
        //分页参数
        dto.setPage((page-1)*dto.getSize());
        //分页查询待人工审核文章
        List<WmNewsVO> listAndPage = wmNewsMapper.findListAndPage(dto);
        //查询待人工审核文章总数
        long count = wmNewsMapper.findListCount(dto);
        //返回结果
        PageResponseResult result = new PageResponseResult(page,dto.getSize(),count,listAndPage);
        result.setHost(webSite);
        return result;
    }



    @Autowired
   private WmUserMapper wmUserMapper;
    /**查看文章详情 功能实现
     *
     * @param id
     * @return
     */
    @Override
    public ResponseResult findWmNewsVo(Integer id) {
        //参数检查
        if(id==null){
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID,"请传入正确id");
        }
        //查询文章
        WmNews wmNews = getById(id);
        if(wmNews==null){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"作者还未发布任何文章");
        }
        //查询作者
        WmUser wmUser = null;
        if(wmNews.getUserId()!=null){
            wmUser = wmUserMapper.selectById(wmNews.getUserId());
        }
        //封装vo对象返回
        WmNewsVO wmNewsVO = new WmNewsVO();
        BeanUtils.copyProperties(wmNews,wmNewsVO);
        if(wmUser!=null){
            wmNewsVO.setAuthorName(wmUser.getName());
        }
        ResponseResult result = ResponseResult.okResult(wmNewsVO);
        result.setHost(webSite);
        return result;
    }


    /**人工审核  文章状态修改
     *
     * @param status  2  审核失败  4 审核成功
     * @param dto
     * @return
     */
    @Override
    public ResponseResult updateStatus(Short status, NewsAuthDTO dto) {
        //检查数据
        if(dto==null||dto.getId()==null){
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID,"请传入正确的参数");
        }
        //根据id查询文章
        WmNews wmNews = wmNewsMapper.selectById(dto.getId());
        if(wmNews==null){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"查询不到该文章");
        }
        //文章不能是已经发布的文章 状态为9
        if(WemediaConstants.WM_NEWS_PUBLISH_STATUS.equals(wmNews.getStatus())){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW,"该文章已发布不能进行此操作");
        }
        //修改文章状态
        wmNews.setStatus(status);
        //若文章审核未通过查看文章是否有未通过原因
        if(StringUtils.isNotBlank(dto.getMsg())){
            wmNews.setReason(dto.getMsg());
        }
        updateById(wmNews);

        //  通知定时发布文章
        //获取创建时间
        long publishTime = wmNews.getPublishTime().getTime();
        //获取当前时间
        long xianzaiTime = new Date().getTime();
        //现在 - 创建 == 发布
        long remainTime = publishTime - xianzaiTime;
        // 发布文章
        rabbitTemplate.convertAndSend(PublishArticleConstants.DELAY_DIRECT_EXCHANGE
                //发送到哪个消息队列
                , PublishArticleConstants.PUBLISH_ARTICLE_ROUTE_KEY
                //设置作者id
                , wmNews.getId()
                //设置消息
                , (message)->{                              // 延时消息 必设置
                    message.getMessageProperties().setHeader("x-delay",remainTime<=0?0:remainTime);
                    return message;
                }
        );
        log.info("立即发布文章通知成功发送，文章id : {}", wmNews.getId());

        return ResponseResult.okResult();
    }

    /**保存文章封面和素材的关联关系 方法实现
     *
     * @param dto
     * @param contentUrls
     * @param wmNews
     */
    private void saveRelativeInfoForCover(WmNewsDTO dto, List<String> contentUrls, WmNews wmNews) {
        //获取前端传入的图片路径集合
        List<String> images = dto.getImages();
        //判断生成封面是否需要自动生成封面
        if(WemediaConstants.WM_NEWS_TYPE_AUTO.equals(dto.getType())){
            //判断自动生成封面图片数量
            if(CollectionUtils.isEmpty(contentUrls)){
                wmNews.setType(WemediaConstants.WM_NEWS_NONE_IMAGE);

            }else if(contentUrls.size()>0&&contentUrls.size()<=2){
                wmNews.setType(WemediaConstants.WM_NEWS_SINGLE_IMAGE);
              images =  contentUrls.stream().limit(1).collect(Collectors.toList());
            }else {
                wmNews.setType(WemediaConstants.WM_NEWS_MANY_IMAGE);
                images =  contentUrls.stream().limit(3).collect(Collectors.toList());
            }
            if(CollectionUtils.isNotEmpty(contentUrls)){
                wmNews.setImages(imageListToStr(images,webSite));
            }else {
                wmNews.setImages(null);
            }
            //修改封面和素材的关联关系
            updateById(wmNews);
        }

        if(CollectionUtils.isNotEmpty(images)){
          images =   images.stream().map(url->url.replaceAll(webSite,"")).distinct().collect(Collectors.toList());
        }
        //保存素材和封面的关联关系
        saveRelativiInfo(images,wmNews.getId(),WemediaConstants.WM_IMAGE_REFERENCE);
    }

    @Autowired
    private WmMaterialMapper wmMaterialMapper;

    /**保存文章和素材关联关系 方法实现
     *
     * @param imagUrls
     * @param newsId
     * @param type
     */
    private void saveRelativiInfo(List<String> imagUrls, Integer newsId, Short type) {
        //根据图片列表及用户ID获取素材列表
       List<Integer>  ids =  wmMaterialMapper.selectRelationsIds(imagUrls,WmThreadLocalUtils.getUser().getId());
        System.out.println(ids);
       //判断素材是否缺失 检查id的数量是否小于imagUrls的长度
        if(ids.size()<imagUrls.size()){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"素材已经失效");
        }
        //得到素材id列表批量保存
        wmNewsMaterialMapper.saveRelations(ids,newsId,type);

    }

    /**抽取所有素材的路径集合方法实现
     *
     * @param contentMaps
     * @return
     */
    private List<String> parseContentImages(List<Map> contentMaps) {
        return contentMaps.stream()
                //筛选type为image的数据(图片路径)
                .filter(m -> WemediaConstants.WM_NEWS_TYPE_IMAGE.equals(m.get("type")))
                //获取图片路径
                .map(m -> (String)m.get("value"))
                //去除前缀 webSite
                .map(m -> m.replaceAll(webSite,""))
                //去重
                .distinct()
                //收集
                .collect(Collectors.toList());
    }

    //操作文章与素材关联表的mapper
    @Autowired
    private WmNewsMaterialMapper wmNewsMaterialMapper;


    /**保存或修改文章抽取方法
     *
     * @param wmNews
     */
    private void saveOrUpdateWm(WmNews wmNews) {
        //1.补全wmNews信息
        //创建时间
        wmNews.setCreatedTime(new Date());
        //默认上架
        wmNews.setEnable(WemediaConstants.WM_NEWS_UP);
        //用户id
        wmNews.setUserId(WmThreadLocalUtils.getUser().getId());
        //提交时间
        wmNews.setSubmitedTime(new Date());
        //2.如果id为空则直接保存
        if (wmNews.getId()==null) {
            save(wmNews);
        }else {
            //id不为空则 先删除素材与文章关系
            wmNewsMaterialMapper.delete(Wrappers.<WmNewsMaterial>lambdaQuery().eq(WmNewsMaterial::getNewsId,wmNews.getId()));
            //修改文章
            updateById(wmNews);
        }
    }

    /**将图片机集合转化为字符串  以逗号拼接
     *
     * @param images
     * @param webSite
     * @return
     */
    private String imageListToStr(List<String> images, String webSite) {
        //stream流转化
        return  images.stream()
                //将website路径去除
                .map((url)->url.replaceAll(webSite,""))
                //去重
                .distinct()
                //收集
                .collect(Collectors.joining(","));
    }
}
